package com.wwwarehouse.contract.orders.temp;


import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.android.flexbox.FlexboxLayout;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.time_pick.utils.DatePickUtils;
import com.wwwarehouse.common.eventbus_event.ImportOrdersEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.DateUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.contract.bean.KeywordsBean;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.core.CustomOrdersMapBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

/**
 * 订单自定义规则审核界面
 * Created by ShineF on 2017/8/14 0014.
 */

public class ImportOrdersDetailsCustomFragment extends BaseFragment implements View.OnClickListener {

    private LinearLayout mLlCard;
    private FlexboxLayout mFlexLayout;
    private RelativeLayout mRlTime;
    private TextView mTvTime;
    private String mStartTime;
    private Button mBtnSubmit;
    private String mEndTime;
    private StateLayout mStateLayout;
    private RadioButton mCustomBtn;
    private RadioButton mAllBtn;
    private RadioGroup mRgConditionType;
    private EditText mEtPrice2;
    private EditText mEtNumber2;
    private EditText mEtPrice1;
    private EditText mEtNumber1;
    private String loadStartTime = "";
    private String loadEndTime = "";
    private KeywordsBean mData;
    private ArrayList<TextView> mTextList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_import_orders_details_custom, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLlCard = $(R.id.ll_card);
        mCustomBtn = $(R.id.rb_import_orders_one);
        mAllBtn = $(R.id.rb_import_orders_two);
        mRgConditionType = $(R.id.rg_condition_type);
        mRlTime = $(R.id.rl_buy_time);
        mStateLayout = $(R.id.sl_state);
        mEtPrice1 = $(R.id.et_price_one);
        mEtPrice2 = $(R.id.et_price_two);
        mEtNumber1 = $(R.id.et_number_one);
        mEtNumber2 = $(R.id.et_number_two);
        mFlexLayout = $(R.id.rbl_view);
        mTvTime = $(R.id.tv_show_time);
        mBtnSubmit = $(R.id.btn_import_custom_submit);
        mBtnSubmit.setEnabled(false);
        mBtnSubmit.setSelected(false);
        Drawable drawable_one = ContextCompat.getDrawable(mActivity, R.drawable.selector_radio_button);
        drawable_one.setBounds(0, 0, 60, 60);
        mCustomBtn.setCompoundDrawables(drawable_one, null, null, null);
        Drawable drawable_two = ContextCompat.getDrawable(mActivity, R.drawable.selector_radio_button);
        drawable_two.setBounds(0, 0, 60, 60);
        mAllBtn.setCompoundDrawables(drawable_two, null, null, null);
        mRlTime.setOnClickListener(this);
        mBtnSubmit.setOnClickListener(this);
        mEtPrice1.addTextChangedListener(new MyTextWatcher(R.id.et_price_one));
        mEtPrice2.addTextChangedListener(new MyTextWatcher(R.id.et_price_two));
        mEtNumber1.addTextChangedListener(new MyTextWatcher(R.id.et_number_one));
        mEtNumber2.addTextChangedListener(new MyTextWatcher(R.id.et_number_two));
        mEtPrice1.setOnFocusChangeListener(new MyChangedFocusListener(R.id.et_price_one));
        mEtPrice2.setOnFocusChangeListener(new MyChangedFocusListener(R.id.et_price_two));
        mEtNumber2.setOnFocusChangeListener(new MyChangedFocusListener(R.id.et_number_two));
        mEtNumber1.setOnFocusChangeListener(new MyChangedFocusListener(R.id.et_number_one));
        mLlCard.setVisibility(View.INVISIBLE);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ImportOrdersDetailsCustomFragment) {
            mActivity.setTitle(R.string.import_orders_setting);
        }
    }

    @Override
    public void requestDatas() {
        mStateLayout.showProgressView(true);
        mTextList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("codeType", "TRADE_AUDIT_KEYWORD");
        map.put("handleCode", "");
        loadData(ContractConstant.GET_IMPORT_ORDERS_KEYWORDS, map, 1);
    }

    /**
     * 动态添加关键字
     *
     * @param bean 关键字模型信息
     */
    public void setKeywords(final KeywordsBean.TRADEAUDITKEYWORDBean bean) {
        final TextView tv = new TextView(mActivity);
        tv.setBackgroundResource(R.drawable.selector_single_select_button_text);
        tv.setText(bean.getName());
        tv.setGravity(Gravity.CENTER);
        FlexboxLayout.LayoutParams params = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, ConvertUtils.dip2px(mActivity, 5), ConvertUtils.dip2px(mActivity, 5));
        tv.setLayoutParams(params);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv.setFocusable(true);
                tv.setFocusableInTouchMode(true);
                tv.requestFocus();
                tv.requestFocusFromTouch();
                bean.setSelected(!bean.isSelected());
                if (bean.isSelected()) {
                    v.setSelected(true);
                    tv.setTextColor(ContextCompat.getColor(mActivity, R.color.common_color_c1_337cff));
                } else {
                    v.setSelected(false);
                    tv.setTextColor(ContextCompat.getColor(mActivity, R.color.common_color_c7_96999e));
                }
                setButtonStatus();
            }
        });
        mFlexLayout.addView(tv);
        mTextList.add(tv);
    }


    /**
     * 设置关键字的点击状态
     */
    public void setKeywordSelected() {
        for (KeywordsBean.TRADEAUDITKEYWORDBean tradeauditkeywordBean : mData.getTRADE_AUDIT_KEYWORD()) {
            for (TextView textView : mTextList) {
                if (textView.getText().equals(tradeauditkeywordBean.getName()) && tradeauditkeywordBean.isSelected()) {
                    textView.setSelected(true);
                    textView.setTextColor(ContextCompat.getColor(mActivity, R.color.common_color_c1_337cff));
                    break;
                }
            }
        }
    }


    /**
     * 请求
     *
     * @param url  请求的url
     * @param map  请求的params
     * @param what 请求的what
     */
    public void loadData(String url, Map map, int what) {
        NoHttpUtils.httpPost(url, map, new NoHttpUtils.OnResponseListener() {
            @Override
            public void onSucceed(CommonClass commonClass, int what) {
                switch (what) {
                    case 1:
                        if ("0".equals(commonClass.getCode())) {
                            mData = JSON.parseObject(commonClass.getData().toString(), KeywordsBean.class);
                            setData();
                        }
                        break;
                }
            }

            @Override
            public void onFailed(String result, int what) {

            }

            @Override
            public void onFinish(int what) {

            }
        }, what);
    }

    /**
     * 设置加载后数据
     */
    public void setData() {
        for (KeywordsBean.TRADEAUDITKEYWORDBean bean : mData.getTRADE_AUDIT_KEYWORD()) {
            setKeywords(bean);
        }
        Bundle bundle = getArguments();
        if (null != bundle) {
            CustomOrdersMapBean mapBean = (CustomOrdersMapBean) bundle.getSerializable("eventData");
            if (mapBean != null) {
                HashMap map = mapBean.getMap();
                String conditionType = (String) map.get("conditionType");
                String dateStart = (String) map.get("dateStart");
                String dateStop = (String) map.get("dateStop");
                String maxPrice = (String) map.get("maxPrice");
                String maxQty = (String) map.get("maxQty");
                String minPrice = (String) map.get("minPrice");
                String minQty = (String) map.get("minQty");
                String keyWords = (String) map.get("keyWords");
                if ("1".equals(conditionType)) {
                    mCustomBtn.setChecked(true);
                } else if ("2".equals(conditionType)) {
                    mAllBtn.setChecked(true);
                }
                if (!"".equals(dateStart) && !"".equals(dateStop)) {
                    setLayoutHeight();
                    mTvTime.setText(dateStart + getResources().getString(R.string.to) + dateStop);
                }
                if (null != maxPrice) {
                    mEtPrice2.setText(maxPrice);
                }
                if (null != minPrice) {
                    mEtPrice1.setText(minPrice);
                }
                if (null != maxQty) {
                    mEtNumber2.setText(maxQty);
                }
                if (null != minQty) {
                    mEtNumber1.setText(minQty);
                }
                if (null != keyWords) {
                    String[] split = keyWords.split(",");
                    for (String str : split) {
                        for (KeywordsBean.TRADEAUDITKEYWORDBean tradeauditkeywordBean : mData.getTRADE_AUDIT_KEYWORD()) {
                            if (str.equals(tradeauditkeywordBean.getName())) {
                                tradeauditkeywordBean.setSelected(true);
                                break;
                            }
                        }
                    }
                    setKeywordSelected();
                }
                setButtonStatus();
            }
//            ImportOrdersSettingInfo.TradeAuditRuleBean tradeAuditRule = bundle.getParcelable("data");
//            if (null != tradeAuditRule) {
//                if (0 != tradeAuditRule.getDateStart())
//                    loadStartTime = DateUtils.getData(String.valueOf(tradeAuditRule.getDateStart()));
//                if (0 != tradeAuditRule.getDateStop())
//                    loadEndTime = DateUtils.getData(String.valueOf(tradeAuditRule.getDateStop()));
//            }
        }
        mStateLayout.showContentView();
        mLlCard.setVisibility(View.VISIBLE);
    }

    /**
     * 动态设置付款时间Layout的高度
     */
    public void setLayoutHeight() {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mRlTime.getLayoutParams();
        params.height = ConvertUtils.dip2px(mActivity, 70);
        mRlTime.setLayoutParams(params);
        mTvTime.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.rl_buy_time) {
            DatePickUtils.showDateAndTimeDialog(mActivity, loadStartTime, getResources().getString(R.string.start_time), new DatePickUtils.OnDateTimeSelectedListener() {
                @Override
                public void onDateTimeSelected(String date) {
                    mStartTime = date;
                    DatePickUtils.showDateAndTimeDialog(mActivity, loadEndTime, getResources().getString(R.string.end_time), new DatePickUtils.OnDateTimeSelectedListener() {
                        @Override
                        public void onDateTimeSelected(String date) {
                            mEndTime = date;
                            if (-1 == DateUtils.compareDate(mEndTime, mStartTime)) {
                                ToastUtils.showToast("结束时间不能早于开始时间");
                            } else {
                                setLayoutHeight();
                                mTvTime.setText(mStartTime + getResources().getString(R.string.to) + date);
                                setButtonStatus();
                            }
                        }
                    });

                }
            });

        } else if (i == R.id.btn_import_custom_submit) {//                ImportOrdersDetailsSubmitFragmentTemp submitFragment = new ImportOrdersDetailsSubmitFragmentTemp();
//                Bundle bundle = new Bundle();
//                bundle.putString("startTime", mStartTime);
//                bundle.putString("endTime", mEndTime);
//                submitFragment.setArguments(bundle);
//                pushFragment(submitFragment);
            if (checkEdit()) {
                HashMap<String, String> map = new HashMap<>();
                String time = mTvTime.getText().toString();
                if (!"".equals(time)) {
                    String[] split = mTvTime.getText().toString().split(getResources().getString(R.string.to));
                    mStartTime = split[0];
                    mEndTime = split[1];
                } else {
                    mStartTime = "";
                    mEndTime = "";
                }
                if (mRgConditionType.getCheckedRadioButtonId() == R.id.rb_import_orders_one) {
                    map.put("conditionType", "1");
                } else {
                    map.put("conditionType", "2");
                }
                map.put("dateStart", mStartTime);
                map.put("dateStop", mEndTime);
                map.put("maxPrice", mEtPrice2.getText().toString());
                map.put("maxQty", mEtNumber2.getText().toString());
                map.put("minPrice", mEtPrice1.getText().toString());
                map.put("minQty", mEtNumber1.getText().toString());
                StringBuilder sb = new StringBuilder();
                for (KeywordsBean.TRADEAUDITKEYWORDBean bean : mData.getTRADE_AUDIT_KEYWORD()) {
                    if (bean.isSelected()) {
                        sb.append(bean.getName());
                        sb.append(",");
                    }
                }
                if (sb.toString().equals("")) {
                    map.put("keyWords", "-1");
                } else {
                    map.put("keyWords", sb.toString().substring(0, sb.toString().length() - 1));
                }

                EventBus.getDefault().post(new ImportOrdersEvent(map, "customDetails"));
                popFragment();
            } else {
                mBtnSubmit.setFocusable(true);
                mBtnSubmit.setFocusableInTouchMode(true);
                mBtnSubmit.requestFocus();
                mBtnSubmit.requestFocusFromTouch();
            }

        }
    }

    /**
     * 自定义TextWatch
     */
    private class MyTextWatcher implements TextWatcher {

        private int mId;

        MyTextWatcher(int id) {
            this.mId = id;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (mId == R.id.et_price_one) {
                setEditPoint(mEtPrice1, s);

            } else if (mId == R.id.et_price_two) {
                setEditPoint(mEtPrice2, s);

            }
            setButtonStatus();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    /**
     * 控制小数点后面两位
     *
     * @param mET 要控制的EditText
     * @param s   输入的字符
     */
    public void setEditPoint(EditText mET, CharSequence s) {
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                mET.setText(s);
                mET.setSelection(s.length());
            }
        }
        if (s.toString().trim().equals(".")) {
            s = "0" + s;
            mET.setText(s);
            mET.setSelection(2);
        }

        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                mET.setText(s.subSequence(0, 1));
                mET.setSelection(1);
            }
        }
    }

    /**
     * 自定义焦点改变监听
     */
    private class MyChangedFocusListener implements View.OnFocusChangeListener {

        private int mId;

        MyChangedFocusListener(int id) {
            this.mId = id;
        }

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            String maxNumber = mEtNumber2.getText().toString();
            String minNumber = mEtNumber1.getText().toString();
            String maxPrice = mEtPrice2.getText().toString();
            String minPrice = mEtPrice1.getText().toString();
            if (mId == R.id.et_price_two) {
                if (!"".equals(minPrice) && !"".equals(maxPrice)) {
                    if (Double.parseDouble(minPrice) > Double.parseDouble(maxPrice)) {
                        mEtPrice2.setText("");
                        ToastUtils.showToast("最小金额不能大于最大金额");
                    }
                }

            } else if (mId == R.id.et_number_two) {
                if (!"".equals(minNumber) && !"".equals(maxNumber)) {
                    if (Double.parseDouble(minNumber) > Double.parseDouble(maxNumber)) {
                        mEtNumber2.setText("");
                        ToastUtils.showToast("最小数量不能大于最大数量");
                    }
                }

            } else if (mId == R.id.et_price_one) {
                if (!"".equals(minPrice) && !"".equals(maxPrice)) {
                    if (Integer.parseInt(minPrice) > Integer.parseInt(maxPrice)) {
                        mEtPrice1.setText("");
                        ToastUtils.showToast("最小金额不能大于最大金额");
                    }
                }

            } else if (mId == R.id.et_number_one) {
                if (!"".equals(minNumber) && !"".equals(maxNumber)) {
                    if (Integer.parseInt(minNumber) > Integer.parseInt(maxNumber)) {
                        mEtNumber1.setText("");
                        ToastUtils.showToast("最小数量不能大于最大数量");
                    }
                }

            }
        }
    }

    /**
     * 设置button状态
     */
    public void setButtonStatus() {
        if (mTvTime.getVisibility() == View.VISIBLE
                || (!"".equals(mEtNumber1.getText().toString()) && !"".equals(mEtNumber2.getText().toString()))
                || (!"".equals(mEtPrice1.getText().toString()) && !"".equals(mEtPrice2.getText().toString()))
                || getIsSelectKeywords()) {
            mBtnSubmit.setEnabled(true);
            mBtnSubmit.setSelected(true);
        } else {
            mBtnSubmit.setEnabled(false);
            mBtnSubmit.setSelected(false);
        }
    }

    public boolean getIsSelectKeywords() {
        boolean isSelected = false;
        for (TextView textView : mTextList) {
            if (textView.isSelected()) {
                isSelected = true;
                break;
            }
        }
        return isSelected;
    }


    public boolean checkEdit() {
        String maxNumber = mEtNumber2.getText().toString();
        String minNumber = mEtNumber1.getText().toString();
        String maxPrice = mEtPrice2.getText().toString();
        String minPrice = mEtPrice1.getText().toString();
        if (!"".equals(minPrice) && !"".equals(maxPrice) && !"".equals(minNumber) && !"".equals(maxNumber)) {
            return !(Integer.parseInt(minNumber) > Integer.parseInt(maxNumber) || Double.parseDouble(minPrice) > Double.parseDouble(maxPrice));
        } else if (!"".equals(minPrice) && !"".equals(maxPrice)) {
            return !(Double.parseDouble(minPrice) > Double.parseDouble(maxPrice));
        } else
            return !(!"".equals(minNumber) && !"".equals(maxNumber)) || !(Integer.parseInt(minNumber) > Integer.parseInt(maxNumber));
    }
}
